<template>
  <basic-dialog
    fullscreen
    :visible.sync="quoteVisible"
    :title="'报价信息'"
    :showFooter="false"
    :handleClose="handleCloseDialog"
    :handleOpen="handleOpenDialog"
  >
    <div>
      <el-card shadow="never" class="form-card">
        <el-form
          ref="quoteForm"
          :model="formData"
          :rules="formValidate"
          label-width="100px"
        >
          <el-col :span="8">
            <el-form-item label="供应商名称:" prop="supplierName">
              <el-input v-model="formData.supplierName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运费承担方:" prop="freightPayer">
              <el-select
                v-model="formData.freightPayer"
                @change="handleChangefreightPayer"
                :disabled="isReadOnly"
              >
                <el-option
                  v-for="option in freightBearerList"
                  :key="option.sysTypeId"
                  :value="option.sysTypeId"
                  :label="option.sysTypeName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运费:" prop="freightPrice">
              <el-input
                v-model.trim="formData.freightPrice"
                :maxlength="32"
                show-word-limit
                :disabled="uneditFreight() || isReadOnly"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商代码:" prop="supplierCode">
              <el-input v-model="formData.supplierCode" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票类型:">
              <el-input v-model="formData.invoiceTypeStr" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率:" prop="taxRate">
              <el-select
                v-model="formData.taxRate"
                :disabled="!isMulttaxRate || isReadOnly"
              >
                <el-option
                  v-for="option in isMulttaxRate ? taxRate2Options : taxRateList"
                  :key="option.sysTypeId"
                  :value="option.sysTypeId"
                  :label="option.sysTypeName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-card>
      <el-card class="sourcing-table-card" shadow="never">
        <el-row slot="header" type="flex" justify="space-between" align="middle">
          <span>数据列表</span>
          <div class="operating-area" v-if="!isReadOnly">
            <div class="time-picker">
              <el-date-picker
                style="margin-right: 10px"
                size="mini"
                v-model="priceExpireTime"
                placeholder="批量维护价格有效期"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="'23:59:59'"
                @change="priceExpireTimeChange"
              />
              <el-date-picker
                v-model="workableArrivalTime"
                placeholder="落实到货时间统一配置"
                type="datetime"
                size="mini"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="'23:59:59'"
                @change="handleArrivalTimeChange"
              />
            </div>
            <el-button class="exportBtn" size="mini" v-if="!isSynergy" type="primary" @click="handleExportQuoteDtl"
            >导出</el-button
            >
            <el-upload
              v-if="!isSynergy"
              ref="importBatchFileUpload"
              class="upload-quote"
              action="/srm-api/selfPurchaseSkuQuote/importSkuQuote"
              :data="fileParam"
              :on-success="onUploadsuccessForBatch"
              :before-upload="beforeFileUploadForBatch"
              :on-error="onUploadErrorForBatch"
              :show-file-list="false"
            >
              <el-button size="mini" type="primary" :loading="importBtnLoading"
              >导入</el-button
              >
            </el-upload>
          </div>
        </el-row>
        <BasicList
          :loading="tableInfo.loading"
          :show-select-col="false"
          :show-pagination="false"
          :data-source="tableInfo.list"
          :columns="tableInfo.columns"
          :tableHeight="500"
          @handleRowChange="handleRowChange"
        />
        <div class="total-price">
          <span>合计金额小写：{{ totalPriceInfo.allSkuTotalPrice }}元</span>
          <el-divider direction="vertical"></el-divider>
          <span>合计金额大写：{{ totalPriceInfo.allSkuTotalPriceStr }}</span>
        </div>
      </el-card>
      <el-row v-if="!isReadOnly" type="flex" justify="end">
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleCalculateCost">计算成本</el-button>
        <el-button :loading="temporarySaveLoading" v-if="!isQuoteDone" type="primary" @click="handleTemporarySave">暂存</el-button>
        <el-button :loading="finishLoading" type="primary" @click="handleFinishQuote">完成报价</el-button>
      </el-row>
      <el-row v-else type="flex" justify="end">
        <el-button @click="handleCloseDialog">取消</el-button>
      </el-row>
    </div>
  </basic-dialog>
</template>
<script>
import { mapState } from 'vuex';
import { toFixedCustomize } from '@/utils/bizUtils';
import BasicDialog from '@/pages/sourcing/components/BasicDialog';
import BasicList from '@/pages/sourcing/components/BasicList';
import {
  queryQuoteDetailService,
  calcAssistNumService, // 计算辅数量
  calcCostPriceService, // 计算成本
  finishQuoteService, // 完成报价
  temporarySaveService, // 暂存报价
} from '@api/sourcing/selfPurchaseInquiry'
import { QUOTE_INFO_TABLE_COLUMNS } from '../../constants'

export default {
  props: [
    'quoteVisible',
    'isSynergy',
    'isQuoteDone',
    'sourcingSupplierId',
    'selfPurchaseBillId',
    'isReadOnly'
  ],
  components: {
    BasicDialog,
    BasicList
  },
  data () {
    return {
      importBtnLoading: false,
      temporarySaveLoading: false, // 暂存loading
      finishLoading: false, // 完成报价loading
      workableArrivalTime: '',
      priceExpireTime: '',
      formData: {},
      formValidate: {
        freightPayer: [
          { required: true, message: '运费承担方不能为空', trigger: 'change' }
        ],
        taxRate: [
          { required: true, message: '税率不能为空', trigger: 'change' }
        ],
        freightPrice: [
          {
            pattern: /^\d+(\.{0,1}\d+){0,1}$/,
            message: '请输入正确格式运费',
            trigger: 'change'
          }
        ]
      },
      tableInfo: {
        list: [],
        columns: QUOTE_INFO_TABLE_COLUMNS,
        loading: false
      },
      taxRate2List: [],
      totalPriceInfo: {
        allSkuTotalPrice: '',
        allSkuTotalPriceStr: '',
      },
      sourcingSupplierInfo: {
        sourcingSupplierId: '',
        selfPurchaseBillId: '',
      },
    }
  },

  computed: {
    ...mapState('sourcing/purchaseDetail', {
      taxRateList: (state) => state.taxRateList, // 税率
      freightBearerList: (state) => state.freightBearerList, // 运费承担方
    }),
    taxRate2Options () {
      return this.taxRateList.filter((item) => {
        return this.taxRate2List.includes(item.sysTypeId + '');
      });
    },
    isMulttaxRate () {
      return this.taxRate2List?.length > 1
    },
    fileParam () {
      return {
        selfPurchaseBillId: this.sourcingSupplierInfo.selfPurchaseBillId,
        sourcingSupplierId: this.sourcingSupplierInfo.sourcingSupplierId
      };
    }
  },
  methods: {
    // 计算成本
    handleCalculateCost () {
      this.$refs.quoteForm.validate((valid) => {
        if (valid) {
          const skuQuotes = this.tableInfo.list.map((item) => ({
            sourcingSkuQuoteId: item.selfPurchaseSkuQuoteId,
            skuUnit: item.skuUnit,
            assistSkuUnit: item.assistSkuUnit,
            skuNum: item.skuNum,
            assistSkuNum: item.assistSkuNum,
            adjustedSkuNum: item.adjustedSkuNum,
            unitPrice: item.unitPrice || 0,
            assistUnitPrice: item.assistUnitPrice || 0,
            addPriceType: item.addPriceType,
            rebateRatio: item.rebateRatio,
          }));
          const {
            freightPayer,
            freightPrice,
            invoiceType,
            taxRate,
          } = this.formData;
          const params = {
            freightPayer,
            freightPrice: Number(freightPrice),
            invoiceType,
            taxRate,
            skuQuotes
          };
          this.calcCostPriceAction(params)
        }
      });
    },
    // 计算成本接口调用
    async calcCostPriceAction (param) {
      const res = await calcCostPriceService(param, state => { this.tableInfo.loading = state })
      if (res?.data) {
        const { skuQuotes, allSkuTotalPrice, allSkuTotalPriceStr } = res.data;
        this.totalPriceInfo = {
          allSkuTotalPrice,
          allSkuTotalPriceStr,
        }
        if (skuQuotes && skuQuotes.length > 0) {
          this.tableInfo.list.forEach(item => {
            skuQuotes.forEach(sku => {
              if (item.selfPurchaseSkuQuoteId === sku.sourcingSkuQuoteId) {
                item.sharePrice = sku.sharePrice; // 运费分摊金额
                item.costPrice = sku.costPrice; // 成本价
                item.totalPrice = sku.totalPrice; // 金额小计
              }
            })
          })
        }
      }
    },
    // 辅进价、最终数量调整联动
    handleRowChange (data) {
      const { prop, row, val } = data;
      // 调整后数量变更
      if (prop == 'adjustedSkuNum') {
        this.calcAssistNumAction({
          adjustSkuNum: val,
          actualConvertRatio: row.actualConvertRatio
        }).then(res => {
          row.assistSkuNum = res.data;
        })
      }
      // 辅进价变更
      if (prop == 'assistUnitPrice' && row.adjustedSkuNum) {
        // 主进价 = 辅进价 * 辅数量 / 调整后数量
        row.unitPrice = toFixedCustomize((row[prop] * row.assistSkuNum) / row.adjustedSkuNum, 1000);
      }
    },
    // 计算辅数量
    async calcAssistNumAction (param) {
      const res = await calcAssistNumService(param, state => { this.tableInfo.loading = state })
      return res;
    },
    // 落实到货时间统一配置
    handleArrivalTimeChange (val) {
      if (val && (Number(new Date(val) < Number(new Date())))) {
        return this.$message.warning('落实到货时间不能小于当前时间');
      }
      if (val) {
        this.tableInfo.list.forEach((item) => {
          item.workableArrivalTime = val;
        });
      }
    },
    // 批量维护报价有效期
    priceExpireTimeChange (val) {
      if (val && (Number(new Date(val) < Number(new Date())))) {
        return this.$message.warning('价格有效期不能小于当前时间');
      }
      if (val) {
        this.tableInfo.list.forEach((item) => {
          item.priceExpireTime = val;
        });
      }
    },
    // 导出
    handleExportQuoteDtl () {
      let selfPurchaseBillId = this.sourcingSupplierInfo.selfPurchaseBillId;
      let sourcingSupplierId = this.sourcingSupplierInfo.sourcingSupplierId;
      if (selfPurchaseBillId && sourcingSupplierId) {
        window.location.href = `${window.location.origin}/srm-api/selfPurchaseSkuQuote/exportSkuQuote?selfPurchaseBillId=${selfPurchaseBillId}&sourcingSupplierId=${sourcingSupplierId}`;
      } else {
        this.$message.error('导出异常');
      }
    },
    // 上传校验
    beforeFileUploadForBatch (file) {
      this.importBtnLoading = true;
      const fileExt = file.name.replace(/.+\./, '');
      const fileTypeArr = ['xls', 'xlsx'];
      const isRightType = fileTypeArr.includes(fileExt.toLowerCase());
      if (!isRightType) {
        this.$message.error('请上传.xls、.xlsx格式的文件!');
        this.importBtnLoading = false;
      }
      return isRightType;
    },
    // 上传成功
    onUploadsuccessForBatch (res) {
      this.importBtnLoading = false;
      if (res && res.code == 200) {
        this.$message.success('导入成功');
        this.queryQuoteDetail();
      } else {
        this.$message.error('导入失败');
      }
    },

    onUploadErrorForBatch () {
      this.importBtnLoading = false;
      this.$message.error('导入失败，请重试。');
    },
    // 查询报价详情
    async queryQuoteDetail () {
      const res = await queryQuoteDetailService({ ...this.sourcingSupplierInfo }, state => { this.tableInfo.loading = state })
      if (res) {
        const {
          allSkuTotalPrice,
          allSkuTotalPriceStr,
          selfPurchaseSkuQuoteList,
          sourcingSupplierDto
        } = res.data
        this.tableInfo.list = selfPurchaseSkuQuoteList;
        this.totalPriceInfo = {
          allSkuTotalPrice,
          allSkuTotalPriceStr
        }
        const {
          supplierName,
          supplierCode,
          supplierId,
          freightPayer,
          invoiceTypeStr,
          invoiceType,
          taxRate,
          freightPrice,
          taxRate2
        } = sourcingSupplierDto
        this.formData = {
          supplierName,
          supplierCode,
          supplierId,
          freightPayer,
          invoiceTypeStr,
          invoiceType,
          taxRate,
          freightPrice
        }
        // 税率2字段解析
        this.taxRate2List = taxRate2 ? [...new Set(taxRate2.split(','))] : [];
      }
    },
    // 打开弹窗执行操作
    handleOpenDialog () {
      this.sourcingSupplierInfo = {
        sourcingSupplierId: this.sourcingSupplierId,
        selfPurchaseBillId: this.selfPurchaseBillId,
      }
      this.workableArrivalTime = '';
      this.priceExpireTime = '';
      this.queryQuoteDetail()
    },
    // 关闭弹窗执行操作
    handleCloseDialog () {
      this.$emit('update:quoteVisible', false);
    },
    // 修改运费承担方
    handleChangefreightPayer (val) {
      this.formData.freightPrice = 0;
    },
    // 非我司承担运费（40357）时 运费可编辑
    uneditFreight () {
      return this.formData.freightPayer != 40357
    },
    // 判断已填写单价但未填写落实到货时间
    isEmptyArrivalTime (data) {
      return data.some((item) => !item.workableArrivalTime);
    },
    // 暂存
    handleTemporarySave () {
      this.$refs.quoteForm.validate((valid) => {
        if (valid) {
          const sourcingSupplierDto = {
            ...this.sourcingSupplierInfo,
            ...this.formData
          }
          const { list } = this.tableInfo;
          this.temporarySaveAction({
            sourcingSupplierDto,
            skuQuoteList: list.filter(item => item.unitPrice)
          })
        }
      })
    },
    // 暂存接口调用
    async temporarySaveAction (param) {
      const res = await temporarySaveService(param, state => { this.temporarySaveLoading = state })
      if (res) {
        this.$message.success('暂存成功')
      }
    },
    // 完成报价
    handleFinishQuote (type) {
      this.$refs.quoteForm.validate((valid) => {
        if (valid) {
          const { list } = this.tableInfo
          const sourcingSupplierDto = {
            ...this.sourcingSupplierInfo,
            ...this.formData
          }
          // 协同供应商完成报价
          if (this.isSynergy) {
            const params = {
              sourcingSupplierDto,
              skuQuoteList: list.filter(item => item.skuStatus == 200)
            };
            this.finishQuoteAction(params)
            return;
          }
          const submitData = {
            sourcingSupplierDto,
            skuQuoteList: list.filter(item => item.unitPrice && item.unitPrice != 0 && item.assistUnitPrice)
          }
          // 检验单价
          if (submitData.skuQuoteList.length == 0) {
            return this.$message.warning('请填写单价');
          }
          // 校验落实到货期
          if (submitData.skuQuoteList.some(item => !item.adjustedSkuNum)) {
            return this.$message.warning('报价商品需填写调整后数量');
          }
          // 校验落实到货期
          if (submitData.skuQuoteList.some(item => !item.workableArrivalTime)) {
            return this.$message.warning('报价商品需填写落实到货时间');
          }
          // 供应商为我司且运费 = 0
          if (this.formData.freightPayer == 40357 && this.formData.freightPrice <= 0) {
            this.$confirm('供应商为我司承担运费，请先落实运费后再进行报价完成', '提示', {
              type: 'warning'
            })
              .then(() => {
                this.unquotedGoodsConfirm(list, submitData)
              })
              .catch(() => {});
          } else {
            this.unquotedGoodsConfirm(list, submitData)
          }
        }
      });
    },
    // 判断是否存在未报价商品
    unquotedGoodsConfirm (list, submitData) {
      if (list.some((item) => !item.unitPrice)) {
        this.$confirm('存在未报价商品，您确定要完成报价吗?', '提示', {
          type: 'warning'
        })
          .then(() => {
            this.finishQuoteAction(submitData)
          })
          .catch(() => {});
      } else {
        this.finishQuoteAction(submitData)
      }
    },
    // 完成报价接口调用
    async finishQuoteAction (param) {
      const res = await finishQuoteService(param, state => { this.finishLoading = state })
      if (res) {
        this.$message.success('操作成功')
        this.handleCloseDialog()
        this.$emit('updateSupplierTableData')
      }
    }
  }
}
</script>
<style lang="less" scoped>
  .form-card {
    margin-bottom: 10px;
    /deep/.el-select {
      width: 100%;
    }
  }
  .sourcing-table-card {
    margin-bottom: 10px;
    /deep/.el-card__header {
      padding: 12px 20px
    }
  }
  .operating-area {
    float: right;
    .time-picker {
      color: #303133;
      display: inline;
    }
    .exportBtn {
      margin-left: 10px;
    }
  }
  .upload-quote {
    display: inline;
    margin-left: 10px;
  }
  .total-price {
    font-weight: bold;
    margin-top: 10px;
  }
</style>
